"use strict";
/*
 * @Description: Be careful what you wish for
 * @Autor: zzzzzed
 * @Date: 2021-08-12 22:14:38
 * @LastEditors: zzzzzed
 */
/**
 *  224.基本计算器
 *   给你一个字符串表达式 s ，请你实现一个基本计算器来计算并返回它的值。
 *
 *   示例 1：
 *
 *   输入：s = "1 + 1"
 *   输出：2
 *   示例 2：
 *
 *   输入：s = " 2-1 + 2 "
 *   输出：3
 *   示例 3：
 *
 *   输入：s = "(1+(4+5+2)-3)+(6+8)"
 *   输出：23
 *   提示：
 *       1 <= s.length <= 3 * 105
 *       s 由数字、'+'、'-'、'('、')'、和 ' ' 组成
 *       s 表示一个有效的表达式
 *
 *
 */
function calculate(s) {
    let stackAry = [];
    let i = 0;
    let res = 0;
    let sign = 1;
    let temp = '';
    while (i < s.length) {
        if (s[i] === ' ') {
            i++;
            continue;
        }
        if (s[i] === '(') {
            // 入栈
            stackAry.push(res);
            stackAry.push(sign);
            sign = 1;
            res = 0;
            // console.log("===== ", stackAry);
        }
        else if (s[i] === '+') {
            sign = 1;
        }
        else if (s[i] === '-') {
            sign = -1;
        }
        else if (s[i] === ')') {
            // 出栈
            let sign = stackAry.pop();
            let num = stackAry.pop();
            res = num + sign * res;
            // console.log("===== ", stackAry, '=== res', res, sign, num);
        }
        else if (s[i] >= '0' && s[i] <= "9") {
            temp = '';
            while (i < s.length && s[i] >= '0' && s[i] <= "9") {
                temp += s[i];
                i++;
            }
            let item = parseInt(temp);
            res += sign * item;
            console.log("res == ", res, sign, item);
            i--;
        }
        i++;
    }
    // let set = new Set();
    // set.remove()
    // console.log(stackAry);
    return res;
}
console.log("====== test1 ===== ");
console.log('====== ', calculate('1 + 1'));
console.log("====== test2 ===== ");
console.log('====== ', calculate(' 2-1 + 2 '));
console.log("====== test3 ===== ");
console.log('====== ', calculate('(1+(4+5+2)-3)+(6+8)'));
console.log("====== test4 ===== ");
console.log('====== ', calculate('- (3 + (4 + 5))'));
